package cn.sc.allinpay.allfavour.module.allin;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;

import com.allinpay.usdk.core.data.BaseData;
import com.allinpay.usdk.core.data.RequestData;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import cn.pai.common.utils.AmtUtils;
import cn.sc.allinpay.allfavour.R;
import cn.sc.allinpay.allfavour.business.common.app.Global;
import cn.sc.allinpay.allfavour.business.common.data.OrderPaymentInfo;
import cn.sc.allinpay.allfavour.business.common.data.PosInfo;
import cn.sc.allinpay.allfavour.business.common.data.SpOrderInfo;

/**
 * description：
 * author：pany
 * on 2018/8/22 09:43
 */
public class AllinUtils {

    public static final String PACKAGENAME = "com.allinpay.usdk";
    public static final String CLASSNAME = "com.allinpay.usdk.MainActivity";

    // 获取 USDK 信息
    public static final void callSign(Activity activity, int req) {
        Intent intent = new Intent();
        intent.setClassName(PACKAGENAME, CLASSNAME);
        Bundle bundle = new Bundle();

        RequestData requestData = new RequestData();
        requestData.putValue(BaseData.BUSINESS_ID, "900300005"); // 获取设备信息

        bundle.putSerializable(RequestData.KEY_ERTRAS, requestData);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent, req);
    }

    public static final void callScan(Activity activity, int req) {
        Intent intent = new Intent();
        intent.setClassName(PACKAGENAME, CLASSNAME);
        Bundle bundle = new Bundle();

        RequestData requestData = new RequestData();
        requestData.putValue(BaseData.BUSINESS_ID, "600000001"); // 获取设备信息

        bundle.putSerializable(RequestData.KEY_ERTRAS, requestData);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent, req);
    }

    public static final void printOrder(SpOrderInfo orderInfo, boolean isMerchant,boolean isCancel, Activity activity, int req) {
        Intent intent = new Intent();
        intent.setClassName(PACKAGENAME, CLASSNAME);
        Bundle bundle = new Bundle();

        RequestData requestData = new RequestData();
        requestData.putValue(BaseData.BUSINESS_ID, "900300003"); // 获取设备信息
        requestData.putValue(BaseData.PRINT_VERSION, "1");
        List<RequestData> lists = printLists(orderInfo, isMerchant, isCancel, activity);
        requestData.putValue(BaseData.PRINT_APPEND_CONTENT, lists);//每一组打印后换行
        bundle.putSerializable(RequestData.KEY_ERTRAS, requestData);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent, req);
    }

    public static final List<RequestData> printLists(SpOrderInfo orderInfo, boolean isMerchant, boolean isCancel, Activity activity)   {
        List<RequestData> lists = new ArrayList<RequestData>();

        RequestData contentStyle = new RequestData();
        Bitmap bmp = BitmapFactory.decodeResource(activity.getResources(), R.drawable.logo);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 压缩位图
        byte[] compressImag = baos.toByteArray();
        String icon = Base64.encodeToString(compressImag, Base64.DEFAULT);
        contentStyle.putValue(BaseData.PRINT_APPEND_PIC, icon);//需要打印的图片（Bitmap格式）图片转换成字符串的形式进行传递
        contentStyle.putValue(BaseData.PRINT_APPEND_LOCATE, "3");//0 – 左对齐   默认, 1 -  行中开始-左对齐, 2 – 右对齐, 3 – 行居中, 4 – 左对齐居中, 5 – 右对齐居中
        lists.add(contentStyle);
        if (isMerchant) {
            RequestData contentStyle1 = new RequestData();
            contentStyle1.putValue(BaseData.PRINT_APPEND_TEXT, "商户存根联\n");//需要打印的文字,注意：字数过多自行添加换行符（\n）
            contentStyle1.putValue(BaseData.PRINT_APPEND_LOCATE, "3");//0 – 左对齐   默认, 1 -  行中开始-左对齐, 2 – 右对齐, 3 – 行居中, 4 – 左对齐居中, 5 – 右对齐居中
            lists.add(contentStyle1);
        } else {
            RequestData contentStyle1 = new RequestData();
            contentStyle1.putValue(BaseData.PRINT_APPEND_TEXT, "持卡人联\n");//需要打印的文字,注意：字数过多自行添加换行符（\n）
            contentStyle1.putValue(BaseData.PRINT_APPEND_LOCATE, "3");//0 – 左对齐   默认, 1 -  行中开始-左对齐, 2 – 右对齐, 3 – 行居中, 4 – 左对齐居中, 5 – 右对齐居中
            lists.add(contentStyle1);
        }


        Global global = Global.getInstance();
        PosInfo posInfo = global.getPosInfo();

        RequestData contentStyle8 = new RequestData();
        contentStyle8.putValue(BaseData.PRINT_APPEND_TEXT, "商户名:" + posInfo.getMer_name() + "\n");//需要打印的文字,注意：字数过多自行添加换行符（\n）
        lists.add(contentStyle8);

        RequestData contentStyle2 = new RequestData();
        contentStyle2.putValue(BaseData.PRINT_APPEND_TEXT, "商户号:" + posInfo.getMer_id() + "\n");//需要打印的文字,注意：字数过多自行添加换行符（\n）
        lists.add(contentStyle2);

        if (orderInfo.getOrderPayment() != null && orderInfo.getOrderPayment().size() != 0) {
            OrderPaymentInfo orderPaymentInfo = orderInfo.getOrderPayment().get(0);
            RequestData contentStyle31 = new RequestData();
            contentStyle31.putValue(BaseData.PRINT_APPEND_TEXT, "交易单号:" + orderPaymentInfo.getTrxId() + "\n");//需要打印的文字,注意：字数过多自行添加换行符（\n）
            lists.add(contentStyle31);

            int paymentFrom = orderPaymentInfo.getPaymentFrom();
            String payFrom = "扫码支付";
            if (paymentFrom == 0) {
                payFrom = "微信支付";
            } else if (paymentFrom == 1) {
                payFrom = "支付宝支付";
            } else if (paymentFrom == 2) {
                payFrom = "手机 QQ 支付";
            } else if (paymentFrom == 3) {
                payFrom = "银联支付";
            }

            if (isCancel) {
                payFrom = payFrom + "撤销";
            }

            RequestData contentStyle32 = new RequestData();
            contentStyle32.putValue(BaseData.PRINT_APPEND_TEXT, "交易类型:" + payFrom + "\n");//需要打印的文字,注意：字数过多自行添加换行符（\n）
            contentStyle32.putValue(BaseData.PRINT_APPEND_SIZE, "30");//16 – 小字体, 24 -  中字体  默认, 32 – 大字体
            lists.add(contentStyle32);

            if (isCancel) {
                RequestData contentStyle33 = new RequestData();
                contentStyle33.putValue(BaseData.PRINT_APPEND_TEXT, "时间:" + orderPaymentInfo.getPaymentTime() + "\n");//需要打印的文字,注意：字数过多自行添加换行符（\n）
                lists.add(contentStyle33);
            } else {
                RequestData contentStyle33 = new RequestData();
                contentStyle33.putValue(BaseData.PRINT_APPEND_TEXT, "时间:" + orderInfo.getLastUpdateTime() + "\n");//需要打印的文字,注意：字数过多自行添加换行符（\n）
                lists.add(contentStyle33);
            }
            RequestData contentStyle34 = new RequestData();
            contentStyle34.putValue(BaseData.PRINT_APPEND_TEXT, "金额:" + AmtUtils.changeF2Y(AmtUtils.changeY2F(orderPaymentInfo.getPaymentAmount())) + "\n");//需要打印的文字,注意：字数过多自行添加换行符（\n）
            contentStyle34.putValue(BaseData.PRINT_APPEND_SIZE, "30");//16 – 小字体, 24 -  中字体  默认, 32 – 大字体
            lists.add(contentStyle34);
        }

        RequestData contentStyle10 = new RequestData();
        contentStyle10.putValue(BaseData.PRINT_APPEND_TEXT, "\n终端号:"+ posInfo.getTermNo() + "             操作员:"+posInfo.getOperator_id()+"\n");//需要打印的文字,注意：字数过多自行添加换行符（\n）
        lists.add(contentStyle10);

        RequestData contentStyle322 = new RequestData();
        contentStyle322.putValue(BaseData.PRINT_APPEND_TEXT, "\n---------------通联客服:95193---------------");//需要打印的文字,注意：字数过多自行添加换行符（\n）
        contentStyle322.putValue(BaseData.PRINT_APPEND_SIZE, "20");//16 – 小字体, 24 -  中字体  默认, 32 – 大字体

        lists.add(contentStyle322);

        return lists;
    }


    // paymentByCard, 刷卡支付
    public static final void cardPayment(Activity activity, String transCheck, String amount, int req) {
        Intent intent = new Intent();
        intent.setClassName(PACKAGENAME, CLASSNAME);
        Bundle bundle = new Bundle();
        RequestData requestData = new RequestData();
        requestData.putValue(BaseData.BUSINESS_ID, "100100001");
        requestData.putValue(BaseData.TRANS_CHECK, transCheck);
        requestData.putValue(BaseData.AMOUNT, AllinUtils.formatAmount(amount));
        bundle.putSerializable(RequestData.KEY_ERTRAS, requestData);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent, req);
    }

    public static final String formatAmount(String amount) {
        long payAmount = Math.round(Double.parseDouble(amount) * 100);
        return String.format("%012d", payAmount);
    }

    // 通过 transCheck 查询订单
    public static final void orderInfoByTransCheck(Activity activity, String transCheck, int req) {
        Intent intent = new Intent();
        intent.setClassName(PACKAGENAME, CLASSNAME);
        Bundle bundle = new Bundle();
        RequestData requestData = new RequestData();
        requestData.putValue(BaseData.BUSINESS_ID, "900100004");
        requestData.putValue(BaseData.TRANS_CHECK, transCheck);

        bundle.putSerializable(RequestData.KEY_ERTRAS, requestData);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent, req);
    }

    // 设置USDK签购单联数为 0
    public static final void configUSDK(Activity activity, int req) {
        Intent intent = new Intent();
        intent.setClassName(PACKAGENAME, CLASSNAME);
        Bundle bundle = new Bundle();
        RequestData requestData = new RequestData();
        requestData.putValue(BaseData.BUSINESS_ID, "900300008");
        requestData.putValue(BaseData.USDK_PARA, "{\"IS_AUTO_SETTLE\":\"1\", \"SETTLE_PERIOD\":\"30\",\"IS_PRINT_SETTLE\":\"0\"}");

        bundle.putSerializable(RequestData.KEY_ERTRAS, requestData);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent, req);
    }

    public static final void callSale(Activity activity, String order_id, String amount, int req) {
        Intent intent = new Intent();
        intent.setClassName(PACKAGENAME, CLASSNAME);
        intent.putExtra("transName", "消费");
        intent.putExtra("orderId", order_id);
        intent.putExtra("amount", AmtUtils.changeF12(amount));
        activity.startActivityForResult(intent, req);
    }

    public static final void callScan(Activity activity, String order_id, String amount, int req) {
        Intent intent = new Intent();
        intent.setClassName(PACKAGENAME, CLASSNAME);
        intent.putExtra("transName", "扫码支付");
        intent.putExtra("orderId", order_id);
        intent.putExtra("amount", AmtUtils.changeF12(amount));
        activity.startActivityForResult(intent, req);
    }

    public static String getSysYear() {
        Calendar date = Calendar.getInstance();
        String year = String.valueOf(date.get(Calendar.YEAR));
        return year;
    }

    /**
     * 消费撤销
     *
     * @param activity
     * @param req
     */
    public static final void callSaleVoid(Activity activity, String amount, String voucherNo, String orderId, int req) {
        Intent intent = new Intent();
        intent.setClassName(PACKAGENAME, CLASSNAME);
        Bundle bundle = new Bundle();
        RequestData requestData = new RequestData();
        requestData.putValue(BaseData.AMOUNT, AllinUtils.formatAmount(amount));
        requestData.putValue(BaseData.ORIG_TRACE_NO, voucherNo);
        requestData.putValue(BaseData.TRANS_CHECK, orderId);
        requestData.putValue(BaseData.BUSINESS_ID, "200100001");

        bundle.putSerializable(RequestData.KEY_ERTRAS, requestData);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent, req);
    }

    /**
     * 重打印
     *
     * @param activity
     * @param req
     */
    public static final void callPrint(Activity activity, String oldTrace, int req) {
        Intent intent = new Intent();
        intent.setClassName(PACKAGENAME, CLASSNAME);
        intent.putExtra("transName", "打印");
        intent.putExtra("oldTrace", oldTrace);
        activity.startActivityForResult(intent, req);
    }

    /**
     * 系统管理
     *
     * @param activity
     * @param req
     */
    public static final void callSysManage(Activity activity, int req) {
        Intent intent = new Intent();
        intent.setClassName(PACKAGENAME, CLASSNAME);
        intent.putExtra("transName", "系统管理");
        activity.startActivityForResult(intent, req);
    }

    /**
     * 收银宝应用是否存在
     *
     * @param context
     * @return
     */
    public static boolean isAppExit(Context context) {
        try {
            context.getPackageManager().getApplicationInfo(PACKAGENAME, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO: handle exception
            return false;
        }
    }

    /**
     * 获取收银宝应用包信息
     *
     * @param context
     * @return
     * @throws PackageManager.NameNotFoundException
     */
    public static PackageInfo getPackageInfo(Context context) throws PackageManager.NameNotFoundException {
        PackageManager pm = context.getPackageManager();
        return pm.getPackageInfo(PACKAGENAME, 0);
    }

    /**
     * 获取收银宝应用版本
     *
     * @param context
     * @return
     * @throws PackageManager.NameNotFoundException
     */
    public static String getVersionName(Context context) {
        PackageInfo pki = null;
        try {
            pki = getPackageInfo(context);
            return pki.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            return e.getMessage();
        }
    }
}
